package com.atguigu.guli.service.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.guli.service.edu.entity.Subject;
import com.atguigu.guli.service.edu.entity.excel.SubjectExcelData;
import com.atguigu.guli.service.edu.mapper.SubjectMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;

@Slf4j   //监听器,读excel表格自动走到这个类
public class SubjectDataListener extends AnalysisEventListener<SubjectExcelData> {
    //这里不能通过autowrite自动注入,因为这类不是组件类,可以写一个构造器,让外界传入
    SubjectMapper subjectMapper;

    //无参构造器
    public SubjectDataListener(SubjectMapper subjectMapper) {
        this.subjectMapper = subjectMapper;
    }

    @Override
    public void invoke(SubjectExcelData subjectExcelData, AnalysisContext analysisContext) {
        String levelOne = subjectExcelData.getLevelOne();
        String levelTwo = subjectExcelData.getLevelTwo();

        LambdaQueryWrapper<Subject> wrapper = new LambdaQueryWrapper();
        //查询数据库
        wrapper.eq(Subject::getTitle, levelOne);
        wrapper.eq(Subject::getParentId, "0");
        Subject levelOneSubject = subjectMapper.selectOne(wrapper);
        //判断数据库里有没有一级分类,没有就添加
        if(levelOneSubject==null){
            levelOneSubject = new Subject();
            //把一级分类存进去
            levelOneSubject.setTitle(levelOne);
            levelOneSubject.setParentId("0");
            levelOneSubject.setSort(0);
            //向数据库添加一级分类
            subjectMapper.insert(levelOneSubject);
        }
        //查二级分类
        wrapper.clear(); //清空之前的条件
        wrapper.eq(Subject::getTitle, levelTwo);
        //查询条件; 一级和二级的连接靠的是getParentId,要想查到二级分类,就要查getParentId
        wrapper.eq(Subject::getParentId, levelOneSubject.getId());
        Integer count = subjectMapper.selectCount(wrapper);
        //判断,不等于0,就说明存在,添加二级分类
        if(count==0){
            Subject sub =  new Subject();
            sub.setParentId(levelOneSubject.getId());
            sub.setSort(0);
            sub.setTitle(levelTwo);
            //添加数据库
            subjectMapper.insert(sub);
        }


    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("excel解析完毕");
    }
}
